<template>
    <div>
        <div class="tenantry-manage">
            <div class="card-box">
                <div class="card-title">基本信息</div>
                <el-form ref="propForm" class="form-wrap" :model="propForm" size="small" :rules="rules">
                    <el-form-item label="出租方名称" prop="lessorName" class="col-one">
                        <el-input maxlength="24" v-model="propForm.lessorName" placeholder="请输入出租方名称，最长为24位"></el-input>
                    </el-form-item>
                    <el-form-item label="出租方类型" prop="lessorType" class="col-two">
                        <el-select
                            v-model="propForm.lessorType"
                            value-key="label"
                            filterable
                            :filter-method="lesseeDataFilter"
                            @change="queryCertificateType"
                            @blur="inintcertificateType"
                        >
                            <el-option
                                v-for="item in lesseeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item prop="certificateType" label="证件类型" class="col-three">
                        <el-select
                            v-model="propForm.certificateType"
                            value-key="label"
                            filterable
                            :filter-method="certificateDataFilter"
                            @blur="inintcertificateNum">
                            <el-option
                                v-for="item in certificateOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="证件号码" prop="certificateNum" class="col-four">
                        <el-input v-bind:disabled="!propForm.certificateType" v-model="propForm.certificateNum"
                                  maxlength="24" placeholder="请先选择出租方类型，再选择证件类型，再填写证件号码"></el-input>
                    </el-form-item>

                    <el-form-item v-show="propForm.lessorType!=0" label="法人代表"
                                  prop="legalPerson" class="col-one">
                        <el-input v-model="propForm.legalPerson" maxlength="18" placeholder="请输入法人代表，最长为18位，不可为空">
                        </el-input>
                    </el-form-item>

                    <el-form-item  v-show=" propForm.lessorType=='1'||propForm.lessorType=='2'||propForm.lessorType=='3'||propForm.lessorType=='4' "  label="通讯地址" prop="address"  class="col-two" >
                        <el-input v-model="propForm.address" maxlength="100" placeholder="请输入通讯地址"></el-input>
                    </el-form-item>
                    <el-form-item v-show="propForm.lessorType=='0'||propForm.lessorType==' '"  label="通讯地址" prop="address"  class="full" >
                        <el-input v-model="propForm.address" maxlength="100" placeholder="请输入通讯地址"></el-input>
                    </el-form-item>
                    <el-form-item label="备注" class="full" prop="remarks">
                        <el-input v-model="propForm.remarks" maxlength="100" placeholder="请输入备注，最长为100位，可为空"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <!-- 如果是新增时，可以切换类型 -->
        <div  class="tenantry-manage">
            <personInfo  v-if="propForm.lessorType=='0'"  :isAdd="isAdd" ref="info1"  :pid="propForm.lessorId" />
            <employeeInfo  v-else :isAdd="isAdd" ref="info2" :pid="propForm.lessorId"/>
        </div>

        <div class="tenantry-manage">
            <div class="card-box">
                <div class="card-title">文件上传</div>
                <div  style="padding:20px 20px 0;">
                    <v-upload
                        type="file"
                        ref="upload"
                        :busId="propForm.lessorId"
                        modelType="client-manage"
                        @onSuccess="onSuccess"
                        v-model="uploadFileList"
                    />
                </div>
            </div>
        </div>
        <div class="tenantry-manage">
            <div class="card-box">
                <el-form size="small" class="but_form">
                    <el-form-item class="col-two">
                        <el-button type="primary" v-throttle="[submit]">保存</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import personInfo from '@/views/wy-lessor/landlord/components/person-info.vue'
import employeeInfo from '@/views/wy-lessor/landlord/components/employee-info.vue'
import { getObj, addObj, putObj, getClientLesseeByCardId } from '@/views/wy-lessor/landlord/api/lessor'
import { validatePhone, validateEmail, validateIdNo } from '~/utils/validate'
import { getDictAndPlease } from "~/utils"
export default {
    components: {
        personInfo,
        employeeInfo
    },
    beforeMount(){
        if(this.$route.query.id){
            this.isAdd = false
            this.propForm.lessorId = this.$route.query.id
            this.init()
        }
        // 获取出租方类型
        this.initClientLesseeType();
        this.queryCertificateType();
    },
    data() {
        return {
            // 表单数据
            propForm: {
                lessorId:'',
                lessorName:'',
                lessorType:'',
                certificateType:'',
                certificateNum:'',
            },
            // 承租方类型列表
            lesseeOptions:[],
            lesseeOptionsCopy:[],
            certificateOptions:[],
            certificateOptionsCopy:[],
            // 上传文件列表
            uploadFileList: [],
            // 是否是新增场景
            isAdd: true,
            // 表单校验
            rules: {
                lessorName: [
                    { required: true, message: "请输入出租方名称", trigger: "blur" },
                ],
                lessorType: [
                    { required: true, message: "请选择出租方类型", trigger: "blur" },
                ],
                certificateType: [
                    { required: true, message: "请选择证件类型", trigger: "blur" },
                ],
                workUnit: [
                ],
                certificateNum: [
                    { required: true, message: "请输入证件号码", trigger: "blur" },
                    { validator: this.validateCertificateNum, trigger: "blur"},
                ],
                phoneNum: [
                    { required: true, message: "请输入手机号码", trigger: "blur" },
                    {validator:validatePhone,trigger: "blur"},
                ],
                email: [
                    { required: true, message: "请输入电子邮件", trigger: "blur" },
                    {validator:validateEmail,trigger: "blur"},
                ],
                legalIdentityCard: [
                    { validator: validateIdNo, trigger: "blur"},
                ],
                remarks: [
                    {min: 0, max: 100, message: "长度在0-100个字符串", trigger: "blur"},
                ]
            },
        }
    },
    methods: {
        validateCertificateNum(rule, value, callback) {
            if(!value){
                return callback()
            }
            if (this.propForm.lessorType==0){
                this.validateCertificateNumOnly(value,callback)
            }else {
                this.validateCertificateNumTwo(value,callback)
            }
        },
        inintcertificateType(){
          this.propForm.certificateType = '',
          this.inintcertificateNum()
        },
        inintcertificateNum(){
          this.propForm.certificateNum = ''
        },
        // 初始化
        async init(){
            const res = await getObj(this.propForm.lessorId);
            if(res.data.code == 0) {
                let data = res.data.data;
                this.propForm = data
                data.lessorType && this.queryCertificateType()
            } else {
                this.$message.error(res.data.msg)
            }
        },
        //初始化承租方类型
        initClientLesseeType(){
            this.lesseeOptions = getDictAndPlease('lessee_type')
            this.lesseeOptionsCopy = this.lesseeOptions
        },
         //点击承租方类型下拉列表后，查询对应的证件类型
        queryCertificateType(){
            if(this.propForm.lessorType==0){
                this.certificateOptions = getDictAndPlease('personage_certificate_type')
                this.certificateOptionsCopy = this.certificateOptions
            }else {
                this.certificateOptions = getDictAndPlease('commercial_certificate_type')
                this.certificateOptionsCopy = this.certificateOptions
            }
        },
        // 表单提交
        async submit(){
            var form = this.$refs[this.propForm.lessorType=='0' ? 'info1':'info2'];
            try {
                var  a=await this.$refs.propForm.validate()
                var  c=await form.$refs.form.validate()
                if(a && c) {
                    this.uploadFileList.length > 0 ? this.$refs.upload.submit('client-manage', this.propForm.lessorId) : this.submitForm()
                }else{
                    return false;
                }
            } catch (e) {
                return false;
            }

        },
        // 文件上传成功
        onSuccess(response, file, fileList) {
            if (response.data) {
                this.submitForm(this.$refs.upload.loadFileList.length > 0 ? '' : response.data)
                //this.$refs.loadFiles.getFiles(response.data);
            } else {
                this.err('提交失败')
            }
        },
        // 表单保存
        submitForm(val = ''){
            let lessorId = this.isAdd ? val : this.propForm.lessorId;
            let ref = this.$refs[this.propForm.lessorType=='0' ? 'info1':'info2'];
            //联系人列表
            let clientLesseeLinkinfos = ref.form.editPersons.map(item => ({...item, lessorId}))
            // 接口参数
            let requestData = {...this.propForm, lessorId,  clientLesseeLinkinfos }
            // 新增
            if(this.isAdd){
                addObj(requestData).then(res => {
                    this.$store.commit("delHistoryRoute", this.$route.fullPath);
                    res.data.code == 0 ? this.$router.back() : this.$message.error(this.isAdd ? '新增失败' : '修改失败');
                })
            } else {
                putObj(requestData).then(res => {
                    this.$store.commit("delHistoryRoute", this.$route.fullPath);
                    res.data.code == 0 ? this.$router.back() : this.$message.error(this.isAdd ? '新增失败' : '修改失败');
                })
            }

        },
        lesseeDataFilter(val) {
            this.formData.lessorType = val;
            if (val) { //val存在
                this.lesseeOptions = this.lesseeOptionsCopy.filter((item) => {
                    if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase())) {
                        return true
                    }
                })
            } else { //val为空时，还原数组
                this.lesseeOptions = this.lesseeOptionsCopy;
            }
        },
        certificateDataFilter(val) {
            this.formData.certificateType = val;
            if (val) { //val存在
                this.certificateOptions = this.certificateOptionsCopy.filter((item) => {
                    if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase())) {
                        return true
                    }
                })
            } else { //val为空时，还原数组
                this.certificateOptions = this.certificateOptionsCopy;
            }
        },
        //验证证件号唯一
        validateCertificateNumTwo(value,callback){
            if (this.propForm.certificateType == 0) {
                /* let Ancode;//营业执照代码的每一个值
                 let Ancodevalue;//营业执照代码每一个值的权重
                 let total = 0;
                 let weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];//加权因子
                 //不用I、O、S、V、Z
                 let str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
                 for (let i = 0; i < value.length - 1; i++) {
                     Ancode = value.substring(i, i + 1);
                     Ancodevalue = str.indexOf(Ancode);
                     total = total + Ancodevalue * weightedfactors[i];
                     //权重与加权因子相乘之和
                 }
                 let logiccheckcode = 31 - total % 31;
                 if (logiccheckcode == 31) {
                     logiccheckcode = 0;
                 }
                 let Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
                 let Array_Str = Str.split(',');
                 logiccheckcode = Array_Str[logiccheckcode];
                 let checkcode = value.substring(17, 18);
                 if (logiccheckcode != checkcode) {
                     callback(new Error('校验失败，请输入正确的18位营业执照！'));
                 }*/
                if (!/^(?!^[A-Z]+$)[A-Z0-9]{8,18}$/.test(value)) {
                    callback(new Error('请输入由大写字母、数字组成或纯数字的8到18位营业执照代码 ！'));
                }

            }
            //税务登记号
            if (this.propForm.certificateType == 3) {
                var reg = /^(?!^[A-Z]+$)[A-Z0-9]{15}$|^(?!^[A-Z]+$)[A-Z0-9]{17}$|^(?!^[A-Z]+$)[A-Z0-9]{18}|^(?!^[A-Z]+$)[A-Z0-9]{20}$/;
                if (!reg.test(value)) {
                    callback(new Error('请输入由大写字母、数字组成或纯数字的15或者17或者18或者20位税务登记号 ！'));
                }
            }
            //统一社会信用代码
            if (this.propForm.certificateType == 2) {
                /* let Ancode;//统一社会信用代码的每一个值
                 let Ancodevalue;//统一社会信用代码每一个值的权重
                 let total = 0;
                 let weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];//加权因子
                 //不用I、O、S、V、Z
                 let str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
                 for (let i = 0; i < value.length - 1; i++) {
                     Ancode = value.substring(i, i + 1);
                     Ancodevalue = str.indexOf(Ancode);
                     total = total + Ancodevalue * weightedfactors[i];
                     //权重与加权因子相乘之和
                 }
                 let logiccheckcode = 31 - total % 31;
                 if (logiccheckcode == 31) {
                     logiccheckcode = 0;
                 }
                 let Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
                 let Array_Str = Str.split(',');
                 logiccheckcode = Array_Str[logiccheckcode];
                 let checkcode = value.substring(17, 18);
                 if (logiccheckcode != checkcode) {
                     callback(new Error('校验失败，请输入正确的18位统一社会信用代码！'));
                 }*/
                if (!/^(?!^[A-Z]+$)[A-Z0-9]{8,18}$/.test(value)) {
                    callback(new Error('请输入由大写字母、数字组成或纯数字的8到18位统一社会信用码 ！'));
                }
            }
            //组织机构代码
            if (this.propForm.certificateType == 1) {
                /*  if (value === "") {
                      callback(new Error("请输入组织机构代码"));
                  } else if (value.length != 9) {
                      callback(new Error("组织机构代码位数不正确"));
                  } else {
                      // var patrn = /^[0-9A-Z]+$/;
                      var reg = /^[0-9A-Z]+$/;
                      if (reg.test(value) == false) {
                          callback(new Error("组织机构代码只可为数字或大写拉丁字母"));
                      } else {
                          var regLast = /^[0-9X]+$/;

                          var lastnum = value.substring(8, 9);

                          if (regLast.test(lastnum) == false) {
                              callback(
                                  new Error("组织机构代码最后一位只可为数字或大写拉丁字母 X")
                              );
                          } else {
                              var ancode;
                              var ancodeWeightValue;
                              var sum = 0;
                              var weightedArray = [3, 7, 9, 10, 5, 8, 4, 2]; //加权因子
                              var str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                              for (var i = 0; i < value.length - 1; i++) {
                                  ancode = value.substring(i, i + 1);
                                  ancodeWeightValue = str.indexOf(ancode);
                                  sum = sum + ancodeWeightValue * weightedArray[i];
                              }
                              var rightLastnum = 11 - (sum % 11);
                              if (rightLastnum == 10) rightLastnum = "X";
                              if (rightLastnum == 11) rightLastnum = "0";
                              if (lastnum != rightLastnum) {
                                  callback(new Error("组织机构代码结构错误！"));
                              }
                          }
                      }
                  }*/


                if (!/^(?!^[A-Z]+$)[A-Z0-9]{8,18}$/.test(value)) {
                    callback(new Error('请输入由大写字母、数字组成或纯数字的8到18位组织机构代码 ！'));
                }
            }
            let certificateType = this.propForm.certificateType;
            let clientLesseeType = this.propForm.clientLesseeType
            if(!this.originalCertificateNum===this.propForm.certificateNum){
                getClientLesseeByCardId({"clientLesseeType":clientLesseeType,"certificateType":certificateType,"certificateNum":value}).then(resp=>{
                    console.log(resp.data,"getClientLesseeByCardId")
                    let data = resp.data
                    if(data.length!=0){
                        return callback(new Error("校验失败，该证件号码已经存在 ！"));
                    }else {
                        callback()
                    }
                })
            }else {
                callback()
            }

        },
        validateCertificateNumOnly (value,callback){
            let certificateType = this.propForm.certificateType;
            let clientLesseeType = this.propForm.clientLesseeType
            if(certificateType==='01'){
                var reg =new RegExp('(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)')
                if (value === '' || value === undefined || value == null) {
                    callback()
                } else {
                    if ((!reg.test(value)) && value !== '') {
                        callback(new Error('请输入正确的身份证号码'))
                    }
                }
            }else if(certificateType==='02'){
                var reg =new RegExp('^[\u4E00-\u9FA5]{1,2}(字第)([0-9a-zA-Z]{4,8})(号?)$')
                if (value === '' || value === undefined || value == null) {
                    callback()
                } else {
                    if ((!reg.test(value)) && value !== '') {
                        callback(new Error('请输入正确的军官证号码，如：军/兵/士/文/职/广/（其他中文） + "字第" + 4到8位字母或数字 + "号"'))
                    }
                }
            }else if(certificateType==='03'){
                reg = new RegExp('^[HMhm]{1}([0-9]{10}|[0-9]{8})$')
                if (value === '' || value === undefined || value == null) {
                    callback()
                } else {
                    if ((!reg.test(value)) && value !== '') {
                        callback(new Error('请输入正确的港澳台证号码，规则如下：H/M + 10位或8位数字'))
                    }
                }
            }else if(certificateType==='04'){
                /*         reg = new RegExp('^([EeKkGgDdSsPpHh]\d{8}$)|(^(([Ee][a-fA-F])|([DdSsPp][Ee])|([Kk][Jj])|([Mm][Aa])|(1[45]))\d{7}$)')*/
                reg = new RegExp('^([a-zA-z]|[0-9]){9}$')
                if (value === '' || value === undefined || value == null) {
                    callback()
                } else {
                    if ((!reg.test(value)) && value !== '') {
                        callback(new Error('请输入正确的护照号码,数字+字母，共9位'))
                    }
                }
            }else if(certificateType==='05'){
                var reg =new RegExp('(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)')
                if (value === '' || value === undefined || value == null) {
                    callback()
                } else {
                    if ((!reg.test(value)) && value !== '') {
                        callback(new Error('请输入正确的华侨身份证号码'))
                    }
                }
            }

            if(!this.originalCertificateNum===this.propForm.certificateNum){
                getClientLesseeByCardId({"clientLesseeType":clientLesseeType,"certificateType":certificateType,"certificateNum":value}).then(resp=>{
                    console.log(resp.data,"getClientLesseeByCardId")
                    let data = resp.data
                    if(data.length!=0){
                        return callback(new Error("校验失败，该证件号码已经存在 ！"));
                    }else {
                        callback()
                    }
                })
            }else {
                callback()
            }

        },

    }
}
</script>

<style scoped lang="scss">
    @import "./scss/edit";
</style>
